<template>
    <el-dialog v-if="popEventVisible" title="请选择" :visible.sync="popEventVisible"  style="text-align: left"
               :before-close="handleCancel" :close-on-click-modal="false">
        <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="按人员" name="choicePerson">
                <div class="tab-list">
                    <!-- 搜索框 -->
                    <el-input class="search-input" placeholder="搜索人员姓名" size="mini" v-model="searchKeyword">
                        <i slot="prefix" class="el-input__icon el-icon-search"></i>
                    </el-input>
                    <el-scrollbar class="scorll-Y">
                        <el-tree class="filter-tree" show-checkbox :data="personTreeData"
                                 @check-change="handleCheckChange" :props="{ label: 'personCommonname' }"
                                 node-key="unid" :default-expanded-keys="expandedKey" :expand-on-click-node="false"
                                 :highlight-current="true" :check-on-click-node="true" :check-strictly="true"
                                 :filter-node-method="filterOrgNode" ref="personTree">
                        </el-tree>
                    </el-scrollbar>
                </div>
            </el-tab-pane>
            <el-tab-pane label="按角色" name="choiceRole">
                <div class="tab-list">
                    <!-- 搜索框 -->
                    <el-input class="search-input" placeholder="搜索角色名称" size="mini" v-model="searchKeyword">
                        <i slot="prefix" class="el-input__icon el-icon-search"></i>
                    </el-input>
                    <el-scrollbar class="scorll-Y">
                        <el-tree class="filter-tree" show-checkbox :data="roleTreeData"
                                 @check-change="handleCheckChange" :props="{ label: 'roleName' }" node-key="unid"
                                 :default-expanded-keys="expandedKey" :expand-on-click-node="false"
                                 :highlight-current="true" :check-on-click-node="true" :check-strictly="true"
                                 :filter-node-method="filterOrgNode" ref="roleTree">
                        </el-tree>
                    </el-scrollbar>
                </div>
            </el-tab-pane>
            <el-tab-pane label="按部门" name="choiceOrg">
                <div class="tab-list">
                    <!-- 搜索框 -->
                    <el-input class="search-input" placeholder="搜索组织名称" size="mini" v-model="searchKeyword">
                        <i slot="prefix" class="el-input__icon el-icon-search"></i>
                    </el-input>
                    <el-scrollbar class="scorll-Y">
                        <el-tree class="filter-tree" show-checkbox :data="orgTreeData" @check-change="handleCheckChange"
                                 :props="{ label: 'orgCommonname' }" node-key="unid"
                                 :default-expanded-keys="expandedKey" :expand-on-click-node="false"
                                 :highlight-current="true" :check-on-click-node="true" :check-strictly="true"
                                 :filter-node-method="filterOrgNode" ref="orgTree">
                        </el-tree>
                    </el-scrollbar>
                </div>
            </el-tab-pane>
        </el-tabs>
        <!-- 选择列表 -->
        <div class="tab-data-list">
            <div class="tab-title" style="line-height:32px;font-weight: 700">
                当前所选数据
                <el-button size="mini" round @click="clearChoice">清空选择</el-button>
            </div>
            <el-scrollbar class="scorll-Y-List">
                <div class="checkList" v-if="personUnidArr.length>0">
                    <span class="checkTitle">已选择人员</span>
                    <div class="person-item" v-for="(pre_item,index) in checkPersonList" :label="pre_item.unid"
                         :key="index">
                        {{pre_item.personCommonname}}
                        <i class="el-icon-circle-close btn-person-cacle" @click="handleDelPerson(pre_item)"/>
                    </div>
                </div>
                <div class="checkList" v-if="roleUnidArr.length>0">
                    <span class="checkTitle">已选择角色</span>
                    <div class="person-item" v-for="(pre_item,index) in checkRoleList" :label="pre_item.unid"
                         :key="index">
                        {{pre_item.roleName}}
                        <i class="el-icon-circle-close btn-person-cacle" @click="handleDelRole(pre_item)"/>
                    </div>
                </div>
                <div class="checkList" v-if="orgUnidArr.length>0">
                    <span class="checkTitle">已选择组织</span>
                    <div class="person-item" v-for="(pre_item,index) in checkOrgList" :label="pre_item.unid"
                         :key="index">
                        {{pre_item.orgCommonname}}
                        <i class="el-icon-circle-close btn-person-cacle" @click="handleDelOrg(pre_item)"/>
                    </div>
                </div>
            </el-scrollbar>
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="handleOk">确定</el-button>
            <el-button @click="handleCancel">取 消</el-button>
        </div>
    </el-dialog>
</template>

<script>
    import {getOrgTree} from "../../api/system/organzation/api.js";
    import {getPersonList} from "../../api/system/person/api.js";
    import {getRoleList} from "../../api/system/role/index.js";
    import PinYinMatch from "pinyin-match";

    export default {
        data()
        {
            return {
                popEventVisible: true,
                multiple: false,
                leftChecked: [],//记录左侧勾选人员unid数组
                activeName: 'choicePerson', // 默认选择的tab页
                expandedKey: [], // 需要默认展开的节点
                promiseStatus: null,
                searchKeyword: "", //关键字搜索
                searchkey: "",
                parameter: {
                    pageNo: 1,
                    pageSize: 100,
                    delFlag: 0,
                    state: 0
                },
                replaceFields: {
                    title: "name", key: "unid"
                },
                //已选人员unid
                personUnidArr: [],
                //已选角色unid
                roleUnidArr: [],
                //已选机构unid
                orgUnidArr: [],
                personTreeData: null,
                roleTreeData: null,
                orgTreeData: null,
            };
        },
        watch: {
            searchKeyword(val)
            {
                console.log(val)
                if (this.activeName == 'choicePerson')
                {
                    this.$refs.personTree.filter(val);
                }
                else if (this.activeName == 'choiceRole')
                {
                    this.$refs.roleTree.filter(val);
                }
                else if (this.activeName == 'choiceOrg')
                {
                    this.$refs.orgTree.filter(val);
                }
            },
        },
        computed:
            {
                checkPersonList()
                {
                    let tampList = [];
                    this.personUnidArr.map(pre_unid =>
                    {
                        let tampArr = pre_unid.split("_");
                        tampList.push({
                            unid: tampArr[0],
                            personCommonname: tampArr[1]
                        });
                    })
                    return tampList;
                },
                checkRoleList()
                {
                    let tampList = [];
                    this.roleUnidArr.map(pre_unid =>
                    {
                        let tampArr = pre_unid.split("_");
                        tampList.push({
                            unid: tampArr[0],
                            roleName: tampArr[1]
                        });
                    })
                    return tampList;
                },
                checkOrgList()
                {
                    let tampList = [];
                    this.orgUnidArr.map(pre_unid =>
                    {
                        let tampArr = pre_unid.split("_");
                        tampList.push({
                            unid: tampArr[0],
                            orgCommonname: tampArr[1]
                        });
                    })
                    return tampList;
                }
            },
        methods: {
            // 切换tab页触发的事件
            handleClick(tab, event)
            {
                console.log("--------------切换tab--------------");
                // this.searchKeyword = "";
                this.getTreeData(tab.name);
            },
            //过滤机构
            filterOrgNode(value, data)
            {
                let fieldName = "";
                if (this.activeName == 'choicePerson')
                {
                    fieldName = "personCommonname"
                }
                else if (this.activeName == 'choiceRole')
                {
                    fieldName = "roleName"
                }
                else if (this.activeName == 'choiceOrg')
                {
                    fieldName = "orgCommonname"
                }
                if (!value || !fieldName) return true;
                return PinYinMatch.match(data[fieldName], value);
            },
            //显示弹窗
            show(showData, replaceFields, multiple, config)
            {
                console.info("--------------初始加载ChooseTabData----------------");
                //首先整理回显人员数据
                if (showData)
                {
                    if (showData.personList && showData.personList.constructor == Array)
                    {
                        let personList = showData.personList;
                        personList.forEach(item =>
                        {
                            this.personUnidArr.push(item.unid + "_" + item.personCommonname);
                        })
                    }
                    if (showData.roleList && showData.roleList.constructor == Array)
                    {
                        let roleList = showData.roleList;
                        roleList.forEach(item =>
                        {

                            this.roleUnidArr.push(item.unid + "_" + item.roleName);
                        })
                    }
                    if (showData.orgList && showData.orgList.constructor == Array)
                    {
                        let orgList = showData.orgList;
                        orgList.forEach(item =>
                        {

                            this.orgUnidArr.push(item.unid + "_" + item.orgCommonname);
                        })
                    }
                }
                this.getTreeData(this.activeName);
                this.multiple = multiple || false;
                this.replaceFields = replaceFields || this.replaceFields;
                // 创建promise
                return new Promise((resolve, reject) =>
                {
                    this.promiseStatus = {
                        resolve,
                        reject,
                    };
                });
            },
            //删除右侧选中的节点数据
            handleDelPerson(P_PersonItem)
            {
                let tampIndex = this.personUnidArr.findIndex(pre_item =>
                {
                    return pre_item == P_PersonItem.unid + "_" + P_PersonItem.personCommonname;
                })
                this.personUnidArr.splice(tampIndex, 1);
                this.removeTreeData(P_PersonItem);
            },
            handleDelRole(P_RoleItem)
            {
                let tampIndex = this.roleUnidArr.findIndex(pre_item =>
                {
                    return pre_item == P_RoleItem.unid + "_" + P_RoleItem.roleName;
                })
                this.roleUnidArr.splice(tampIndex, 1);
                this.removeTreeData(P_RoleItem);
            },
            handleDelOrg(P_OrgItem)
            {
                let tampIndex = this.orgUnidArr.findIndex(pre_item =>
                {
                    return pre_item == P_OrgItem.unid + "_" + P_OrgItem.orgCommonname;
                })
                this.orgUnidArr.splice(tampIndex, 1);
                this.removeTreeData(P_OrgItem);
            },
            // 选择项和右侧选择的数据进行同步
            removeTreeData(P_DataItem)
            {
                if (this.activeName == 'choicePerson')
                {
                    var personTree = this.$refs.personTree.getCheckedKeys();
                    personTree.forEach(item =>
                    {
                        if (item = P_DataItem.unid)
                        {
                            this.$refs.personTree.setChecked(item, false, false);
                        }
                    })
                }
                else if (this.activeName == 'choiceRole')
                {
                    var roleTree = this.$refs.roleTree.getCheckedKeys();
                    roleTree.forEach(item =>
                    {
                        if (item = P_DataItem.unid)
                        {
                            this.$refs.roleTree.setChecked(item, false, false);
                        }
                    })
                }
                else if (this.activeName == 'choiceOrg')
                {
                    var orgTree = this.$refs.orgTree.getCheckedKeys();
                    orgTree.forEach(item =>
                    {
                        if (item = P_DataItem.unid)
                        {
                            this.$refs.orgTree.setChecked(item, false, false);
                        }
                    })
                }
            },
            //确认按钮
            handleOk()
            {
                let personList = this.checkPersonList || [];
                let roleList = this.checkRoleList || [];
                let orgList = this.checkOrgList || [];
                let selects = {
                    personList: personList,
                    roleList: roleList,
                    orgList: orgList
                }
                // 返回选中的人员、角色、部门数据
                this.promiseStatus.resolve({
                    choiceData: selects,
                    replaceFields: this.replaceFields
                });
                this.destroyElement();
            },
            //取消按钮
            handleCancel()
            {
                //清空勾选项
                this.promiseStatus.reject({
                    msg: "取消",
                });
                this.destroyElement();
            },
            // 监听树选择
            handleCheckChange(data, checked, indeterminate)
            {
                if (this.activeName == 'choicePerson')
                {
                    if (checked)
                    {
                        this.personUnidArr.push(data.unid + "_" + data.personCommonname);
                    }
                    else
                    {
                        let tampIndex = this.personUnidArr.findIndex(pre_item =>
                        {
                            return pre_item == data.unid + "_" + data.personCommonname;
                        });
                        if (tampIndex != -1)
                        {
                            this.personUnidArr.splice(tampIndex, 1);
                        }
                    }
                }
                else if (this.activeName == 'choiceRole')
                {
                    if (checked)
                    {
                        this.roleUnidArr.push(data.unid + "_" + data.roleName);
                    }
                    else
                    {
                        let tampIndex = this.roleUnidArr.findIndex(pre_item =>
                        {
                            return pre_item == data.unid + "_" + data.roleName;
                        });
                        if (tampIndex != -1)
                        {
                            this.roleUnidArr.splice(tampIndex, 1);
                        }
                    }
                }
                else if (this.activeName == 'choiceOrg')
                {
                    if (checked)
                    {
                        this.orgUnidArr.push(data.unid + "_" + data.orgCommonname);
                    }
                    else
                    {
                        let tampIndex = this.orgUnidArr.findIndex(pre_item =>
                        {
                            return pre_item == data.unid + "_" + data.orgCommonname;
                        });
                        if (tampIndex != -1)
                        {
                            this.orgUnidArr.splice(tampIndex, 1);
                        }
                    }
                }
            },
            // 获取tree数据
            getTreeData(tabName)
            {
                if (tabName == 'choicePerson')
                {
                    this.getPersonList();
                }
                else if (tabName == 'choiceRole')
                {
                    this.getRoleList();
                }
                else if (tabName == 'choiceOrg')
                {
                    this.getOrgTree();
                }
            },
            //获取人员
            getPersonList()
            {
                this.expandedKey = [];
                if (!this.personTreeData)
                {
                    getPersonList(this.parameter).then((res) =>
                    {
                        this.personTreeData = res.result.data || [];
                        this.setPersonTreeData();
                    });
                }
                else
                {
                    this.setPersonTreeData();
                }
            },
            //获取角色
            getRoleList()
            {
                this.expandedKey = [];
                if (!this.roleTreeData)
                {
                    getRoleList(this.parameter).then((res) =>
                    {
                        this.roleTreeData = res.result.data || [];
                        this.setRoleTreeData();
                    })
                }
                else
                {
                    this.setRoleTreeData();
                }
            },
            //获取机构
            getOrgTree()
            {
                this.expandedKey = [];
                if (!this.orgTreeData)
                {
                    getOrgTree().then((res) =>
                    {
                        this.orgTreeData = res.result || [];
                        this.setOrgTreeData();
                    });
                }
                else
                {
                    this.setOrgTreeData();
                }
            },
            //数据缓存
            setPersonTreeData()
            {
                var checkPersonUnids = [];
                this.personUnidArr.map(pre_unid =>
                {
                    let tampArr = pre_unid.split("_");
                    checkPersonUnids.push(tampArr[0]);
                });
                this.$refs.personTree.setCheckedKeys(checkPersonUnids, true);
            },
            setRoleTreeData()
            {
                var checkRoleUnids = [];
                this.roleUnidArr.map(pre_unid =>
                {
                    let tampArr = pre_unid.split("_");
                    checkRoleUnids.push(tampArr[0]);
                });
                this.$refs.roleTree.setCheckedKeys(checkRoleUnids, true);
            },
            setOrgTreeData()
            {
                this.orgTreeData.forEach((element) =>
                {
                    this.expandedKey.push(element.unid);
                });
                var checkOrgUnids = [];
                this.orgUnidArr.map(pre_unid =>
                {
                    let tampArr = pre_unid.split("_");
                    checkOrgUnids.push(tampArr[0]);
                });
                this.$refs.orgTree.setCheckedKeys(checkOrgUnids, true);
            },
            //清空选择
            clearChoice()
            {
                this.personUnidArr = [];
                this.orgUnidArr = [];
                this.roleUnidArr = [];
                if (this.activeName == 'choicePerson')
                {
                    var personTree = this.$refs.personTree.getCheckedKeys();
                    personTree.forEach(item =>
                    {
                        this.$refs.personTree.setChecked(item, false, false);
                    })
                }
                else if (this.activeName == 'choiceRole')
                {
                    var roleTree = this.$refs.roleTree.getCheckedKeys()
                    roleTree.forEach(item =>
                    {
                        this.$refs.roleTree.setChecked(item, false, false);
                    })
                }
                else if (this.activeName == 'choiceOrg')
                {
                    var orgTree = this.$refs.orgTree.getCheckedKeys();
                    orgTree.forEach(item =>
                    {
                        this.$refs.orgTree.setChecked(item, false, false);
                    })
                }
            },
            //销毁组件
            destroyElement()
            {
                this.popEventVisible = false;
            },
        },
    };
</script>

<style lang="scss" scoped>

    ::v-deep .el-tabs {
        width: 100%;
        padding: 0 15px 0 15px;
        border-right: 1px solid #e6ebf5;
    }

    .tab-data-list {
        width: 100%;

        .tab-title {
            width: 96%;
            margin: 20px 2% 0 2%;
            height: 32px;
            display: flex;
            justify-content: space-between;
        }

        .person-item {
            display: block;
            height: 26px;
            line-height: 26px;
            padding-left: 25px;
        }

        .checkTitle {
            padding-left: 10px;
            color: darkgray;
            height: 28px;
            line-height: 28px;
        }

        .btn-person-cacle {
            cursor: pointer;
            color: red;
            font-size: 14px;
        }

        .scorll-Y-List {
            height: 284px;
            margin-top: 10px;

            ::v-deep .el-scrollbar__wrap {
                overflow-x: hidden;
            }
        }
    }

    ::v-deep .el-dialog__body {
        border-radius: 3px;
        display: flex;
        border: 1px solid #e6ebf5;
        margin: 10px;
        padding: 0;
    }

    .search-input {
        width: 92%;
        margin: 20px 10px 0;
        height: 32px;

        ::v-deep .el-input__inner {
            border-radius: 100px;
        }
    }

    .scorll-Y {
        height: 230px;
        margin-top: 10px;

        ::v-deep .el-scrollbar__wrap {
            overflow-x: hidden;
        }
    }

</style>